<?php

namespace app\index\controller\home;

use app\common\service\DouyinMiniProgramMessageService;
use app\common\service\MiniProgramMessageService;
use app\common\service\SubscribeMessageService;
use app\index\model\UM as UM;
use app\index\service\HomeService;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use think\APP;
use think\Request as Request;

/**
 * Home 控制器
 * Class Home
 * @package app\home\controller
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037509
 */
class Home
{
    // 请求参数
    private Request $request;

    // service
    private HomeService $service;

    public function __construct(Request $request, HomeService $homeService)
    {
        $this->request = $request;
        $this->service = $homeService;
    }

    /**
     * 首页
     * @param \app\index\model\UM|null $user
     * @return ApiResponse
     * @url /home/home/read
     */
    public function read(?UM $user): ApiResponse
    {
        $request = $this->request;

        $data = $this->service->read($user, $request->param());

        // 返回客户端订阅消息
        $subscribe_message_templates = [];
        $service = $this->getSubscribeMessageService($request->header('pf'));
        if ($service) {
            $subscribe_message_templates = $service->getConsultingTemplates();
        }
        $data['subscribe_message_templates'] = $subscribe_message_templates;

        return ApiResponse::success($data);
    }


    private function getSubscribeMessageService($pf): ?SubscribeMessageService
    {
        if ($pf == PT_WX) {
            return \app(MiniProgramMessageService::class);
        }

        if ($pf == PT_TT) {
            return \app(DouyinMiniProgramMessageService::class);
        }

        return null;
    }
}
